<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="下单时间" prop="gsOrderCreateDate">
        <el-date-picker v-model="queryParams.gsOrderCreateDate" value-format="yyyy-MM-dd" type="date"
          placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="送达时间" prop="gsDeliverGoodsDate">
        <el-date-picker v-model="queryParams.gsDeliverGoodsDate" value-format="yyyy-MM-dd" type="date"
          placeholder="请选择送达时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="下单仓库" prop="warehouseName">
        <el-input v-model="queryParams.warehouseName" placeholder="请输入下单仓库" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="送货单号" prop="sendOrderId">
        <el-input v-model="queryParams.sendOrderId" placeholder="请输入送货单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:order:add']">新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:order:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:order:delete']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:order:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-document" size="mini" :disabled="multiple" @click="crateOrder"
          v-hasPermi="['system:order:delivery']" :loading="create_btn_loading">生成送货单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" size="mini">
      <el-table-column type="selection" width="55" align="center" :selectable="checkboxSelect" />
      <el-table-column label="下单仓库" align="center" prop="WAREHOUSENAME" sortable :show-overflow-tooltip="columnShow" />
      <el-table-column label="下单时间" align="center" prop="GS_ORDER_CREATE_DATE" :show-overflow-tooltip="columnShow"
        min-width="135" />
      <el-table-column label="送达时间" align="center" prop="GS_DELIVER_GOODS_DATE" :show-overflow-tooltip="columnShow"
        min-width="90" />
      <el-table-column label="产品编码" align="center" prop="GS_CONCENTRICITY_ID" :show-overflow-tooltip="columnShow"
        min-width="120" />
      <el-table-column label="产品名称" align="center" prop="PRODUCTNAME" :show-overflow-tooltip="columnShow" />
      <el-table-column label="型号" align="center" prop="MODEL" :show-overflow-tooltip="columnShow" />
      <el-table-column label="规格" align="center" prop="SPEC" :show-overflow-tooltip="columnShow" />
      <el-table-column label="品牌" align="center" prop="PRODUCT_BRAND" :show-overflow-tooltip="columnShow" />
      <el-table-column label="订货数量" align="center" prop="GS_ORDER_COUNT" :show-overflow-tooltip="columnShow">
        <template slot-scope="scope">
          <span style="font-size: 15px; font-weight: bold;">{{ scope.row.GS_ORDER_COUNT }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际送货数量" align="center" prop="actSendCount" width="140">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.actSendCount" :precision="2" :step="0.1" :min="0" :max="parseInt(scope.row.GS_ORDER_COUNT)"
            label="描述文字" size="mini" :disabled="!(scope.row.GS_ORDER_DETAIL_STATUS == 9)"></el-input-number>
        </template>
      </el-table-column>

      <el-table-column label="单价" align="center" prop="GS_GOODS_UNITPRICE" :show-overflow-tooltip="columnShow" />
      <el-table-column label="订单状态" align="center" prop="GS_ORDER_DETAIL_STATUS" :show-overflow-tooltip="columnShow">
        <template slot-scope="scope">
          <span v-if="scope.row.GS_ORDER_DETAIL_STATUS == 9">新订单</span>
          <!-- <span v-else-if="scope.row.GS_ORDER_DETAIL_STATUS == 10" style="color:#409EFF ">已收货</span> -->
          <span v-else-if="scope.row.GS_ORDER_DETAIL_STATUS == 13">配送中</span>
          <span v-else-if="scope.row.GS_ORDER_DETAIL_STATUS == 14">已收货</span>
          <span v-else-if="scope.row.GS_ORDER_DETAIL_STATUS == 10">供应商取消</span>
          <span v-else-if="scope.row.GS_ORDER_DETAIL_STATUS == 15">仓库拒收</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商名称" align="center" prop="PROVIDER_NAME" :show-overflow-tooltip="columnShow" />
      <el-table-column label="实际入库数量" align="center" prop="actReciveCount" :show-overflow-tooltip="columnShow" />
      <!-- <el-table-column label="送货单号" align="center" prop="sendOrderId" :show-overflow-tooltip="columnShow" width="130"
        fixed="right">
        <template slot-scope="scope">
          <span style="cursor: pointer;" @click="printOrder(scope.row.sendOrderId)">{{ scope.row.sendOrderId }}</span>
        </template>
      </el-table-column> -->
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" v-if="scope.row.GS_ORDER_DETAIL_STATUS == 9"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 打印 -->
    <printComponent ref="printRef" @update="getList" />
  </div>
</template>

<script>
import { listOrder2Api, newListOrderApi, getOrder, delOrder, addOrder, updateOrder, createSendOrderApi, createNewSendOrderApi, searchSendOrderApi } from "@/api/system/order";
import printComponent from "./orderProcessingFile/print.vue"

export default {
  name: "Order",
  data() {
    return {
      columnShow: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gsOrderTempid: null,
        warehouseName: null,
        gsOrderCreateDate: null,
        gsDeliverGoodsAddr: null,
        gsConcentricityId: null,
        productName: null,
        model: null,
        spec: null,
        productBrand: null,
        gsOrderCount: null,
        gsGoodsUnitprice: null,
        gsDeliverGoodsDate: null,
        gsOrderDetailStatus: 9,
        notifyResult: null,
        providerCode: null,
        providerName: null,
        actSendCount: null,
        actReciveCount: null,
        sendOrderId: null,

        providerName: JSON.parse(localStorage.getItem('User')).dept ? JSON.parse(localStorage.getItem('User')).dept.deptName : '',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      create_btn_loading: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    checkboxSelect(row, index) {
      if (row.GS_ORDER_DETAIL_STATUS == 9) {
        return true
      } else {
        return false
      }
    },

    getFormatDate() {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },

    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder2Api(this.queryParams).then(response => {
        if (response.code == 200) {
          const _data = response.data;
          this.orderList = _data.list.map(item => {
            if (!item.actSendCount) {
              item.actSendCount = item.GS_ORDER_COUNT;
            }
            return item;
          })
          this.total = _data.total;
          this.loading = false;
        } else {
          this.$message.error(response.msg)
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        gsOrderTempid: null,
        warehouseName: null,
        gsOrderCreateDate: null,
        gsDeliverGoodsAddr: null,
        gsConcentricityId: null,
        productName: null,
        model: null,
        spec: null,
        productBrand: null,
        gsOrderCount: null,
        gsGoodsUnitprice: null,
        gsDeliverGoodsDate: null,
        gsOrderDetailStatus: null,
        notifyResult: null,
        providerCode: null,
        providerName: null,
        actSendCount: null,
        actReciveCount: null,
        sendOrderId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 生成送货单
    crateOrder(row = null) {
      let _params = [];
      const _warehouseName = new Set();

      if (this.ids.length > 6) {
        this.$message.warning("一次最多添加6条记录");
        return;
      }

      for (let item of this.orderList) {
        if (this.ids.includes(item.id)) {
          if (item.actSendCount == 0) {
            this.$message.warning("实际送货数量不能为 0");
            return;
          };
          _params.push(item)

          _warehouseName.add(item.WAREHOUSENAME);
        }
      }

      if (_warehouseName.size > 1) {
        this.$message.warning("不能同时选择多个不同仓库");
        return;
      }
      // console.log(_params)
      // return;
      this.create_btn_loading = true;
      createNewSendOrderApi().then(res => {
        if (res.code == 200) {
          this.$refs.printRef.openPrint(
            {
              sendOrderId: res.data.sendOrderId,
              WAREHOUSENAME: _params[0].WAREHOUSENAME,
              GS_DELIVER_GOODS_ADDR: _params[0].GS_DELIVER_GOODS_ADDR,
              GS_DELIVER_GOODS_DATE: _params[0].GS_DELIVER_GOODS_DATE,
              PROVIDER_NAME: _params[0].PROVIDER_NAME,
              lists: _params,
              createdTime: (() => {
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');

                const hour = String(now.getHours()).padStart(2, '0');
                const minute = String(now.getMinutes()).padStart(2, '0');
                const second = String(now.getSeconds()).padStart(2, '0');

                const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
                return formattedDate
              })()
            }
          );
        } else {
          this.$message.error(res.msg)
        }
      }).finally(() => {
        this.create_btn_loading = false;
      })

    },

    // 通过送货单号打印工单
    printOrder(id) {
      searchSendOrderApi({ sendOrderId: id }).then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.$refs.printRef.printOrder({
            sendOrderId: id,
            WAREHOUSENAME: res.data.list[0].WAREHOUSENAME,
            GS_DELIVER_GOODS_ADDR: res.data.list[0].GS_DELIVER_GOODS_ADDR,
            GS_DELIVER_GOODS_DATE: res.data.list[0].GS_DELIVER_GOODS_DATE,
            lists: res.data.list,
            createdTime: res.data.list[0].GS_ORDER_CREATE_DATE
          });
        }
      })
    },


    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      
      this.$modal.confirm('确认删除当前数据项？').then( () => {
        const paramsList = [];
        const _list = Array.isArray(ids) ? ids : [ids]
        this.orderList.forEach(item => {
          if (_list.includes(item.id)) {
            paramsList.push({
              gsOrderTempid: item.GS_ORDER_TEMPID,
              gsConcentricityId: item.GS_CONCENTRICITY_ID
            })
          }
        })
        return delOrder(paramsList);
      }).then((res) => {
        if(res.code == 200) {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        } else {
          this.$modal.msgError(res.msg);
        }

      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  },
  components: {
    printComponent
  }
};
</script>
